package china.song314.abs;

public abstract class AbsPauseThread extends Thread{

	
	
	public AbsPauseThread() {
		super();
	}

	public AbsPauseThread(Runnable target, String name) {
		super(target, name);
	}

	public AbsPauseThread(Runnable target) {
		super(target);
	}

	public AbsPauseThread(String name) {
		super(name);
	}

	public AbsPauseThread(ThreadGroup group, Runnable target, String name,
			long stackSize) {
		super(group, target, name, stackSize);
	}

	public AbsPauseThread(ThreadGroup group, Runnable target, String name) {
		super(group, target, name);
	}

	public AbsPauseThread(ThreadGroup group, Runnable target) {
		super(group, target);
	}

	public AbsPauseThread(ThreadGroup group, String name) {
		super(group, name);
	}


	private boolean isPaused;
	private boolean isStoped;
	
	public void pauseTask() {
		isPaused = true;
	}
	
	public void stopTask() {
		isStoped = true;
	}
	
	public void continueTask() {
		if (isPaused) {
			synchronized (this) {
				if (isPaused) {
					this.notify();
					System.out.println("--- notify  " + isInterrupted());
					isPaused = false;
				}
			}
		}
	}
	
	public boolean isTaskPuased() {
		return isPaused;
	}
	
	public boolean isStopedTask() {
		return isStoped;
	}
	
	@Override
	public void run() {
		
		while (!isStoped) {
			
			if (isPaused) {
			synchronized (this) {
				System.out.println("--- pauseTask  " + isInterrupted());
				try {
					this.wait();
					System.out.println("--- continueTask ");
				} catch (InterruptedException e) {
					e.printStackTrace();
					System.out.println("--- continueTask int InterruptedException" + isInterrupted());
				}
			}
	
			} else {
				doTask();
			}
		}
		
		System.out.println("--- Thread end , isInterrupted : " + isInterrupted());
	}

	abstract void doTask();
	
	
	public static void main(String[] args) {
		
		AbsPauseThread t = new AbsPauseThread() {
			
			@Override
			void doTask() {
				System.out.println(" do task : " + System.currentTimeMillis() + ", " + isInterrupted());
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		
		t.start();
		
		final long time = 3000;
		for (int i = 0; i < 10; i++) {
			try {
				Thread.sleep(time);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			t.pauseTask();
			try {
				Thread.sleep(time);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			t.continueTask();
			try {
				Thread.sleep(time);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		t.stopTask();
	}
	
}
